/**
 * @file player.c
 * @brief COSC361 - MCU Jukebox Project\n
 * Group: Hamish Cumming, Brian Thorne\n
 * Latest source can be obtained using SVN from google's code repository with the following command:\n
 * svn checkout http://mega8-hob.googlecode.com/svn/trunk/ jukebox-hamish-brian\n
 * Description: The main audio player\n
 * Date: 29/5/2008
 */
 
#include "player.h"
#include "tone.h"
#include "song.h" //needs to be included after tone.h
#include "timer.h"

/* Prototypes */
extern void reset_time(void); //this is in main.c

/* File vars */
static unsigned int songIndex = 0; //what song is playing or about to play
static unsigned int songArrayIndex = 0; //how far we are through the song (note)
static unsigned int songTime = 0; //how far we are through the song (time)
static unsigned int mode = MODE_PLAYING;

/**
 * @return True if the player is idle
 */
int player_isIdle()
{
    return (mode==MODE_IDLE);
}

/**
 * @return true if the player is playing
 */
int player_isPlaying()
{
    return (mode==MODE_PLAYING);
}

/**
 * @brief Will only get called when jukebox is on PLAYING mode.
 */
void player_step(int time)
{
    if (songArrayIndex < songs[songIndex]->length)
    {
        play_tone((songs[songIndex]->song[songArrayIndex]));
        if ((time > (songTime + songs[songIndex]->song[songArrayIndex].duration)))
        {
            songTime += songs[songIndex]->song[songArrayIndex].duration;
            songArrayIndex++;
        } 
    } else {
        player_stop();
    }
}

/**
 * @brief Change the song to this index and start playing.
 */
void player_chooseSong(int song)
{
    player_stop();
    if (song < NUM_SONGS)
    {
        songIndex = song;
        player_play_pause();
    }
}

/**
 * @brief Jump to the Previous Song
 */
void player_previous()
{
    player_stop();
    if(songIndex) songIndex--;
    player_play_pause();
}

/**
 * @brief Jump to the next song
 */
void player_next()
{
    player_stop();
    if(songIndex<NUM_SONGS-1) 
    {
        songIndex++;
        player_play_pause();
    }
}

/**
 * @brief If playing, pause. If paused or stopped, play.
 */
void player_play_pause()
{
    if(mode==MODE_IDLE || mode==MODE_PAUSED)
    {
        mode = MODE_PLAYING;
        timer1_reset();
        timer1_overflow();//clear any overflow bits
    } else if(mode==MODE_PLAYING)
    {
        mode = MODE_PAUSED;
    }
}

/**
 * @brief Stop the current playing song and reset song index to start of current song
 */
void player_stop()
{
    reset_time();
    timer1_overflow();//clear any overflow bits
    mode = MODE_IDLE; //Stop
    songArrayIndex = 0;
    songTime = 0;
}

void player_volumeUp(void){};
void player_volumeDown(void){};
